
#include "StdAfx.h"
#include "TreeTextureLoader.h"

namespace LifeSketchTree
{
CRawLoader::CRawLoader()
{
	textureExist = false;
}


CRawLoader::~CRawLoader()
{
	glDeleteTextures(1, &ID);     // Release the image from OpenGL memory.
}


bool CRawLoader::LoadFile(const char *file)
{
	if(textureExist)
		glDeleteTextures(1, &ID);     // Release the image from OpenGL memory.
	
	// Load the image.
	ID = LoadTextureRAW(file, true);
	printf("new texture id: %d\n", ID);
	
	textureExist = true;
	
	return true;
}


GLuint CRawLoader::LoadTextureRAW(const char * filename, int wrap )
{
	int width = 256, height = 256;
	char * data;
	FILE * file;
	GLuint texture = 0;
	
	// open texture data
	file = fopen( filename, "rb" );
	if ( file == NULL ) return 0;
	
	data = (char*)malloc( width * height * 3 );
	
	// read texture data
	fread( data, width * height * 3, 1, file );
	fclose( file );
	
	glGenTextures( 1, &texture );	
	glBindTexture( GL_TEXTURE_2D, texture );
	
	glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
	
	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
					GL_LINEAR_MIPMAP_NEAREST );
	
	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
		
	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
					wrap ? GL_REPEAT : GL_CLAMP );
	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
					wrap ? GL_REPEAT : GL_CLAMP );
	
	gluBuild2DMipmaps( GL_TEXTURE_2D, 3, width, height, GL_RGB, GL_UNSIGNED_BYTE, data );
	
	free( data );
	imageWidth = width;
	imageHeight = height;
	return texture;
}
}
